<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件夹传输系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }
        
        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        
        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }
        
        .content {
            padding: 30px;
        }
        
        .controls {
            display: flex;
            gap: 15px;
            margin-bottom: 30px;
            flex-wrap: wrap;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 600;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-success {
            background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
            color: white;
        }
        
        .btn-warning {
            background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
            color: white;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.2);
        }
        
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }
        
        .folder-list {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .folder-item {
            display: flex;
            align-items: center;
            padding: 15px;
            margin-bottom: 10px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .folder-item:hover {
            transform: translateX(5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.15);
        }
        
        .folder-item.selected {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .folder-icon {
            font-size: 24px;
            margin-right: 15px;
        }
        
        .folder-info {
            flex: 1;
        }
        
        .folder-name {
            font-weight: 600;
            font-size: 16px;
            margin-bottom: 5px;
        }
        
        .folder-size {
            font-size: 14px;
            opacity: 0.7;
        }
        
        .status {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
        }
        
        .status.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .status.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .status.info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .empty-state {
            text-align: center;
            padding: 40px;
            color: #6c757d;
        }
        
        .empty-state .icon {
            font-size: 48px;
            margin-bottom: 15px;
        }
        
        .server-info {
            background: #e3f2fd;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            border-left: 4px solid #2196f3;
        }
        
        .connection-status {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
        }
        
        .connection-status.connected {
            background: #e8f5e8;
            color: #2e7d32;
        }
        
        .connection-status.disconnected {
            background: #ffebee;
            color: #c62828;
        }
        
        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: currentColor;
        }
        
        .settings-panel {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
        }
        
        .settings-title {
            font-weight: 600;
            margin-bottom: 15px;
            color: #495057;
        }
        
        .setting-item {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .setting-label {
            flex: 1;
            font-weight: 500;
        }
        
        .setting-input {
            flex: 2;
            padding: 8px 12px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📁 文件夹传输系统</h1>
            <p>跨电脑文件夹传输解决方案 - 自动解压版本</p>
        </div>
        
        <div class="content">
            <div class="server-info">
                <strong>🌐 服务器状态：</strong>
                <span id="connectionStatus" class="connection-status disconnected">
                    <span class="status-dot"></span>
                    <span id="connectionText">未连接</span>
                </span>
            </div>
            
            <div class="settings-panel">
                <div class="settings-title">⚙️ 解压设置</div>
                <div class="setting-item">
                    <label class="setting-label">自动解压路径：</label>
                    <input type="text" id="extractPath" class="setting-input" 
                           value="C:\Downloads\Extracted" 
                           placeholder="输入解压路径">
                </div>
                <div class="setting-item">
                    <label class="setting-label">
                        <input type="checkbox" id="autoExtract" checked>
                        下载后自动解压
                    </label>
                </div>
            </div>
            
            <div id="status" class="status" style="display: none;"></div>
            
            <div class="controls">
                <button id="refreshBtn" class="btn btn-primary">
                    🔄 刷新文件夹列表
                </button>
                <button id="downloadBtn" class="btn btn-success" disabled>
                    ⬇️ 下载选中文件夹
                </button>
                <button id="uploadBtn" class="btn btn-warning">
                    ⬆️ 上传文件
                </button>
            </div>
            
            <div id="folderList" class="folder-list">
                <div class="empty-state">
                    <div class="icon">📂</div>
                    <p>点击"刷新文件夹列表"开始</p>
                </div>
            </div>
            
            <input type="file" id="fileInput" style="display: none;" multiple>
        </div>
    </div>

    <script>
        class FolderTransferSystem {
            constructor() {
                this.selectedFolders = new Set();
                this.serverUrl = 'http://10.15.4.255:5000'; // 修改为您的服务器地址
                this.init();
            }
            
            init() {
                this.bindEvents();
                this.checkConnection();
                this.loadSettings();
            }
            
            bindEvents() {
                document.getElementById('refreshBtn').addEventListener('click', () => this.refreshFolders());
                document.getElementById('downloadBtn').addEventListener('click', () => this.downloadFolders());
                document.getElementById('uploadBtn').addEventListener('click', () => this.uploadFiles());
                document.getElementById('fileInput').addEventListener('change', (e) => this.handleFileUpload(e));
                document.getElementById('extractPath').addEventListener('change', () => this.saveSettings());
                document.getElementById('autoExtract').addEventListener('change', () => this.saveSettings());
            }
            
            loadSettings() {
                const savedExtractPath = localStorage.getItem('extractPath');
                const savedAutoExtract = localStorage.getItem('autoExtract');
                
                if (savedExtractPath) {
                    document.getElementById('extractPath').value = savedExtractPath;
                }
                if (savedAutoExtract !== null) {
                    document.getElementById('autoExtract').checked = savedAutoExtract === 'true';
                }
            }
            
            saveSettings() {
                const extractPath = document.getElementById('extractPath').value;
                const autoExtract = document.getElementById('autoExtract').checked;
                
                localStorage.setItem('extractPath', extractPath);
                localStorage.setItem('autoExtract', autoExtract);
            }
            
            async checkConnection() {
                try {
                    const response = await fetch(`${this.serverUrl}/api/folders`);
                    this.updateConnectionStatus(response.ok);
                } catch (error) {
                    this.updateConnectionStatus(false);
                }
            }
            
            updateConnectionStatus(connected) {
                const statusEl = document.getElementById('connectionStatus');
                const textEl = document.getElementById('connectionText');
                
                if (connected) {
                    statusEl.className = 'connection-status connected';
                    textEl.textContent = '已连接';
                } else {
                    statusEl.className = 'connection-status disconnected';
                    textEl.textContent = '未连接';
                }
            }
            
            showStatus(message, type = 'info') {
                const statusEl = document.getElementById('status');
                statusEl.textContent = message;
                statusEl.className = `status ${type}`;
                statusEl.style.display = 'block';
                
                setTimeout(() => {
                    statusEl.style.display = 'none';
                }, 5000);
            }
            
            async refreshFolders() {
                const btn = document.getElementById('refreshBtn');
                btn.disabled = true;
                btn.innerHTML = '🔄 刷新中<span class="loading"></span>';
                
                try {
                    const response = await fetch(`${this.serverUrl}/api/folders`);
                    if (!response.ok) throw new Error('获取文件夹列表失败');
                    
                    const data = await response.json();
                    this.renderFolders(data.folders);
                    this.showStatus('文件夹列表刷新成功', 'success');
                    this.updateConnectionStatus(true);
                } catch (error) {
                    this.showStatus(`错误: ${error.message}`, 'error');
                    this.updateConnectionStatus(false);
                } finally {
                    btn.disabled = false;
                    btn.innerHTML = '🔄 刷新文件夹列表';
                }
            }
            
            renderFolders(folders) {
                const folderList = document.getElementById('folderList');
                
                if (folders.length === 0) {
                    folderList.innerHTML = `
                        <div class="empty-state">
                            <div class="icon">📂</div>
                            <p>没有找到文件夹</p>
                        </div>
                    `;
                    return;
                }
                
                folderList.innerHTML = folders.map(folder => `
                    <div class="folder-item ${this.selectedFolders.has(folder.name) ? 'selected' : ''}" 
                         data-folder="${folder.name}">
                        <div class="folder-icon">📁</div>
                        <div class="folder-info">
                            <div class="folder-name">${folder.name}</div>
                            <div class="folder-size">大小: ${this.formatSize(folder.size)}</div>
                        </div>
                    </div>
                `).join('');
                
                // 绑定点击事件
                folderList.querySelectorAll('.folder-item').forEach(item => {
                    item.addEventListener('click', () => this.toggleFolderSelection(item));
                });
            }
            
            toggleFolderSelection(item) {
                const folderName = item.dataset.folder;
                
                if (this.selectedFolders.has(folderName)) {
                    this.selectedFolders.delete(folderName);
                    item.classList.remove('selected');
                } else {
                    this.selectedFolders.add(folderName);
                    item.classList.add('selected');
                }
                
                this.updateDownloadButton();
            }
            
            updateDownloadButton() {
                const downloadBtn = document.getElementById('downloadBtn');
                downloadBtn.disabled = this.selectedFolders.size === 0;
                downloadBtn.textContent = `⬇️ 下载选中文件夹 (${this.selectedFolders.size})`;
            }
            
            async downloadFolders() {
                if (this.selectedFolders.size === 0) {
                    this.showStatus('请先选择要下载的文件夹', 'warning');
                    return;
                }

                const btn = document.getElementById('downloadBtn');
                btn.disabled = true;
                btn.innerHTML = '📂 正在传输到本地<span class="loading"></span>';

                try {
                    // 1. 从服务器获取 ZIP
                    const response = await fetch(`${this.serverUrl}/api/download`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ folders: Array.from(this.selectedFolders) })
                    });

                    if (!response.ok) throw new Error('获取文件夹失败');

                    const blob = await response.blob();

                    // 2. 直接发送到本地接收器（无需用户交互）
                    const formData = new FormData();
                    formData.append('file', blob, 'folders.zip');

                    const localResponse = await fetch('http://127.0.0.1:5001/api/local-receive', {
                        method: 'POST',
                        body: formData
                    });

                    if (!localResponse.ok) throw new Error('本地写入失败');

                    const result = await localResponse.json();
                    this.showStatus(`✅ 文件夹已自动放入：${result.path}`, 'success');

                } catch (error) {
                    this.showStatus(`❌ 传输失败: ${error.message}`, 'error');
                } finally {
                    btn.disabled = false;
                    btn.innerHTML = '📂 下载选中文件夹';
                }
            }
            
            async extractZip(blob, filename) {
                try {
                    this.showStatus('正在解压文件...', 'info');
                    
                    // 使用 JSZip 库解压
                    const JSZip = await this.loadJSZip();
                    const zip = await JSZip.loadAsync(blob);
                    
                    const extractPath = document.getElementById('extractPath').value;
                    
                    // 创建解压路径
                    const extractDir = `${extractPath}\\${filename.replace('.zip', '')}`;
                    
                    // 创建目录
                    await this.createDirectory(extractDir);
                    
                    // 解压所有文件
                    const files = Object.keys(zip.files);
                    for (const filename of files) {
                        const zipEntry = zip.files[filename];
                        if (!zipEntry.dir) {
                            const content = await zipEntry.async('uint8array');
                            await this.writeFile(`${extractDir}\\${filename}`, content);
                        }
                    }
                    
                    this.showStatus(`文件已解压到: ${extractDir}`, 'success');
                } catch (error) {
                    throw new Error(`解压失败: ${error.message}`);
                }
            }
            
            async loadJSZip() {
                if (window.JSZip) return window.JSZip;
                
                return new Promise((resolve, reject) => {
                    const script = document.createElement('script');
                    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js';
                    script.onload = () => resolve(window.JSZip);
                    script.onerror = reject;
                    document.head.appendChild(script);
                });
            }
            
            async createDirectory(path) {
                // 这里需要实现创建目录的逻辑
                // 由于浏览器安全限制，我们需要使用 File System Access API
                try {
                    const dirHandle = await window.showDirectoryPicker();
                    return dirHandle;
                } catch (error) {
                    throw new Error('无法创建目录，请手动选择解压位置');
                }
            }
            
            async writeFile(path, content) {
                // 由于浏览器安全限制，我们提供下载后手动解压的替代方案
                const blob = new Blob([content]);
                this.downloadBlob(blob, path.split('\\').pop());
            }
            
            downloadBlob(blob, filename) {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);
            }
            
            uploadFiles() {
                document.getElementById('fileInput').click();
            }
            
            async handleFileUpload(event) {
                const files = event.target.files;
                if (files.length === 0) return;
                
                const formData = new FormData();
                for (let file of files) {
                    formData.append('file', file);
                }
                
                try {
                    const response = await fetch(`${this.serverUrl}/api/upload`, {
                        method: 'POST',
                        body: formData
                    });
                    
                    if (!response.ok) throw new Error('上传失败');
                    
                    const result = await response.json();
                    this.showStatus(`上传成功: ${result.message}`, 'success');
                } catch (error) {
                    this.showStatus(`上传错误: ${error.message}`, 'error');
                }
                
                // 清空文件输入
                event.target.value = '';
            }
            
            formatSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
        }
        
        // 初始化系统
        document.addEventListener('DOMContentLoaded', () => {
            new FolderTransferSystem();
        });
    </script>
</body>
</html>